package tool

import (
	"bytes"
	"encoding/json"
	"hft/test/mi/loupan/model"
	"regexp"
	"strings"
	"unicode/utf8"

	"golang.org/x/net/html"
)

func ConvertToJSON(str string) (string, error) {
	// Extract key-value pairs using regular expressions
	re := regexp.MustCompile(`"([^"]+)";s:(\d+):"([^"]+)"`)
	matches := re.FindAllStringSubmatch(str, -1)

	// Create a Property instance
	property := model.Lxq{}

	// Parse the key-value pairs
	for _, match := range matches {
		key := match[1]
		value := strings.ReplaceAll(match[3], "\t", "")

		// Set the corresponding field in the Property struct
		switch key {
		case "装修情况":
			property.Decoration = value
		case "物业用途":
			property.PropertyUse = value
		case "产权年限":
			property.Ownership = value
		case "开盘时间":
			property.OpeningTime = value
		case "交房时间":
			property.Delivery = value
		case "楼盘地址":
			property.Address = value
		case "物业公司":
			property.PropertyCo = value
		case "物业费用":
			property.PropertyFee = value
		case "预售许可证":
			property.License = value
		case "开发商":
			property.Developer = value
		case "容积率":
			property.VolumeRate = value
		case "绿化率":
			property.GreeningRate = value
		case "占地面积":
			property.FloorArea = value
		case "建筑面积":
			property.BuildArea = value
		case "楼栋总数":
			property.BuildNum = value
		case "总户数":
			property.UserNum = value
		case "停车位":
			property.ParkingSpace = value
		}

	}

	// Convert the Property struct to JSON
	jsonData, err := json.Marshal(property)
	if err != nil {
		return "", err
	}

	// Convert the JSON byte array to a formatted string
	jsonStr := string(jsonData)

	return jsonStr, nil
}

func ReplaceString(a, b, c string) string {
	if strings.Contains(a, b) {
		return strings.ReplaceAll(a, b, c)
	}
	return a
}

func ProcessImgTags(a string) string {
	re := regexp.MustCompile(`(?s)<img(.*?)>`)
	result := re.ReplaceAllStringFunc(a, func(match string) string {
		if strings.HasSuffix(match, "/>") {
			return match // 以"/>"结尾，不进行替换
		} else if strings.HasSuffix(match, ">") {
			return strings.TrimSuffix(match, ">") + "/>" // 以">"结尾，替换为"/>"
		}
		return match
	})

	return result
}

func CheckTags(text string) int {
	imgRegex := regexp.MustCompile(`<img\b.*?>`)
	videoRegex := regexp.MustCompile(`<video\b.*?>`)

	if imgRegex.MatchString(text) {
		return 1
	} else if videoRegex.MatchString(text) {
		return 2
	} else {
		return 0
	}
}

// 提取纯文本
func ConvertHTMLToPlainText(htmlString string) (plainText string, err error) {
	// 解析HTML字符串
	doc, err := html.Parse(strings.NewReader(htmlString))
	if err != nil {
		return "", err
	}

	// 遍历解析后的HTML节点，提取纯文本内容
	var buf bytes.Buffer
	var visitNode func(node *html.Node)
	visitNode = func(node *html.Node) {
		if node.Type == html.TextNode {
			buf.WriteString(node.Data) // 提取文本内容
		}

		for child := node.FirstChild; child != nil; child = child.NextSibling {
			visitNode(child) // 递归遍历子节点
		}
	}
	visitNode(doc)

	return buf.String(), nil
}

func TruncateString(input string, length int) string {
	if length <= 0 {
		return ""
	}

	// 确保长度不超过字符串的长度
	if length > utf8.RuneCountInString(input) {
		length = utf8.RuneCountInString(input)
	}

	runes := []rune(input)
	truncated := string(runes[:length])

	return truncated
}
